package com.qigao.mall.web.controller.app.user;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.qigao.mall.api.OrderService;
import com.qigao.mall.api.PromGroupService;
import com.qigao.mall.commons.dto.*;
import com.qigao.mall.commons.enums.Result;
import com.qigao.mall.commons.enums.ResultCode;
import com.qigao.mall.commons.exceptions.BusinessException;
import com.qigao.mall.web.config.QiGaoProperties;
import com.qigao.mall.web.utils.RequestUtils;
import com.qigao.mall.web.utils.ValidatorUtil;
import com.qigao.mall.web.vo.PageVo;
import com.qigao.mall.web.vo.app.OrderCreateDetailVo;
import com.qigao.mall.web.vo.app.OrderCreateVo;
import com.qigao.mall.web.vo.app.PromGroupCondVo;
import com.qigao.mall.web.vo.app.PromGroupCreateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 2020-2020
 * FileName: AppPromGroupController
 * Author:   luiz
 * Date:     2020/10/15 14:27
 * Description: 团购
 */
@RestController
@RequestMapping("/app/user/promGroup")
@Api(tags = "App团购相关API",value = "App团购相关API")
public class AppPromGroupController {
    private final Logger logger= LoggerFactory.getLogger(getClass());
    @Resource
    PromGroupService promGroupService;
    @Resource
    OrderService orderService;
    @Resource
    private QiGaoProperties qiGaoProperties;
    //创建团购
    @PostMapping("/create")
    @ApiOperation(value = "创建团购", notes = "创建团购")
    public Result<String> create(@RequestBody PromGroupCreateVo promGroupCreateVo, HttpServletRequest request) {
        //权限校验
        ValidatorUtil.validateEntity(promGroupCreateVo);
        try {
            PromGroupCreateDto promGroupCreateDto=new PromGroupCreateDto();
            BeanUtils.copyProperties(promGroupCreateVo,promGroupCreateDto);
            promGroupCreateDto.setOperUserNo(RequestUtils.getCurrentUserNo(request));
            promGroupCreateDto.setMerNo(qiGaoProperties.getMerNo());
            promGroupCreateDto.setShopNo(qiGaoProperties.getShopNo());
           return promGroupService.create(promGroupCreateDto);
        }catch (Exception e){
            logger.error("创建团购失败:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }
    //根据当前用户获取开团列表
    @PostMapping("/findGroupByCurrentUser")
    @ApiOperation(value = "根据当前用户获取开团列表", notes = "根据当前用户获取开团列表")
    public Result<PageInfo<PromGroupResultDto>> findGroupByCurrentUser(@RequestBody PromGroupCondVo promGroupCondVo, HttpServletRequest request) {
        try {
            String userNo=RequestUtils.getCurrentUserNo(request);
            PromGroupCondDto promGroupCondDto=new PromGroupCondDto();
            promGroupCondDto.setUserNo(userNo);
            promGroupCondDto.setGroupStatus(promGroupCondVo.getGroupStatus());
            promGroupCondDto.setPageNum(promGroupCondVo.getPageNum());
            promGroupCondDto.setPageSize(promGroupCondVo.getPageSize());
            return promGroupService.listPage(promGroupCondDto);
        }catch (Exception e){
            logger.error("根据当前用户获取开团列表失败:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }
    //按照商品查询有效团购列表
    @PostMapping("/findByItemNoAndGroupNo")
    @ApiOperation(value = "按照商品和团购编号查询有效团购列表", notes = "按照商品和团购编号查询有效团购列表")
    public Result<PageInfo<PromGroupResultDto>> findByItemNoAndGroupNo(@RequestBody PromGroupCondVo promGroupCondVo) {
        try {
            return promGroupService.findByItemNoAndGroupNo(promGroupCondVo.getItemNo(),promGroupCondVo.getGroupNo());
        }catch (Exception e){
            logger.error("按照商品和团购编号查询有效团购列表失败:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }
    //按照商品查询有效团购列表
    @PostMapping("/findByItemNo/{itemNo}")
    @ApiOperation(value = "按照商品查询有效团购列表", notes = "按照商品查询有效团购列表")
    public Result<List<PromGroupResultDto>> findByItemNo(@PathVariable("itemNo")String itemNo) {
        try {
            return promGroupService.findByItemNo(itemNo);
        }catch (Exception e){
            logger.error("按照商品查询有效团购列表失败:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }
    //按照团购编号查询团购详情
    @PostMapping("/findByGroupNo/{groupNo}")
    @ApiOperation(value = "按照团购编号查询团购详情", notes = "按照团购编号查询团购详情")
    public Result<PromGroupResultDto> findByGroupNo(@PathVariable("groupNo")String groupNo) {
        try {
            return promGroupService.findByGroupNo(groupNo);
        }catch (BusinessException be){
            logger.error("按照团购编号查询团购详情失败发生业务异常:{}",be);
            return Result.newError(be.getCode(),be.getMsg());
        }catch (Exception e){
            logger.error("按照团购编号查询团购详情失败:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }
    //检查是否已经加入团购
    @GetMapping("/checkJoinGroup/{groupNo}")
    @ApiOperation(value = "检查是否已经加入团购", notes = "检查是否已经加入团购")
    public Result<Boolean> checkJoinGroup(@PathVariable("groupNo")String groupNo,HttpServletRequest request) {
        try {
            return promGroupService.checkJoinGroup(groupNo,RequestUtils.getCurrentUserNo(request));
        }catch (BusinessException be){
            logger.error("[检查是否已经加入团购]发生业务异常:{}",be);
            return Result.newError(be.getCode(),be.getMsg());
        }catch (Exception e){
            logger.error("检查是否已经加入团购失败:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }
    //1.加入团购创建订单
    @PostMapping("/createOrder")
    @ApiOperation(value = "加入团购创建订单", notes = "加入团购创建订单")
    public Result<String> createOrder(@RequestBody OrderCreateVo orderCreateVo, HttpServletRequest request){
        //参数校验
        ValidatorUtil.validateEntity(orderCreateVo,OrderCreateVo.class);
        try{
            if(StringUtils.isEmpty(orderCreateVo.getGroupNo())){
                return Result.newError(ResultCode.COMMON_PARAM_INVALID.getCode(),"团购编号不能为空!");
            }
            OrderCreateDto orderCreateDto=new OrderCreateDto();
            BeanUtils.copyProperties(orderCreateVo,orderCreateDto);
            List<OrderCreateDetailVo> orderCreateDetailVos=orderCreateVo.getOrderCreateDetailVos();
            if(orderCreateDetailVos==null || orderCreateDetailVos.size()==0){
                return Result.newError(ResultCode.COMMON_PARAM_INVALID);
            }
            List orderCreateDtos=new ArrayList();
            for(OrderCreateDetailVo orderCreateDetailVo : orderCreateDetailVos){
                ValidatorUtil.validateEntity(orderCreateDetailVo,OrderCreateDetailVo.class);
                OrderCreateDetailDto orderCreateDetailDto=new OrderCreateDetailDto();
                BeanUtils.copyProperties(orderCreateDetailVo,orderCreateDetailDto);
                orderCreateDetailDto.setCoupAmt(new BigDecimal(orderCreateDetailVo.getCoupAmt()));
                orderCreateDetailDto.setScoreAmt(new BigDecimal(orderCreateDetailVo.getScoreAmt()));
                orderCreateDtos.add(orderCreateDetailDto);
            }
            orderCreateDto.setPayType(orderCreateVo.getPayType().getCode());
            orderCreateDto.setOrderCreateDetailDtoList(orderCreateDtos);
            orderCreateDto.setBuylerId(RequestUtils.getCurrentUserNo(request));
            orderCreateDto.setBuylerName(RequestUtils.getCurrentUserName(request));
            orderCreateDto.setSysName(qiGaoProperties.getSysName());
            return orderService.createOrder(orderCreateDto);
        }catch (BusinessException be){
            logger.error("[创建团购订单]发生业务异常:{}",be);
            return Result.newError(be.getCode(),be.getMsg());
        }catch (Exception e){
            logger.error("[创建团购订单]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

}
